package com.zhucai.credit.repository;

import java.math.BigDecimal;
import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import com.zhucai.credit.model.CreditInvoiceEntity;

/**
 * 
 * @author hsg
 *（发票信息的）Repository
 */
@Repository
public interface CreditInvoiceRepository extends
		PagingAndSortingRepository<CreditInvoiceEntity, Long>,
		JpaSpecificationExecutor<CreditInvoiceEntity>,
		JpaRepository<CreditInvoiceEntity,Long>{


	
	@Transactional
	@Modifying(clearAutomatically = true)
	@Query(value="update tb_xa_invoice_info set invoice_amount = ?1, invoice_code = ?2, invoice_date= ?3, invoice_no = ?4, invoice_file_id = ?5,modify_user = ?7,invoice_file_name =?8   where id = ?6", nativeQuery=true)
	Integer updateInvoice(BigDecimal invoiceAmount, String invoiceCode,
			Date invoiceDate, String invoiceNo, Long invoiceFileId,Long tid, Long userId, String invoiceFileName);

	CreditInvoiceEntity findByTidAndStatusNot(Long tid, int delete);

	//验证发票号
	@Query(value="select count(*)"
			+ " from tb_xa_invoice_info txif"
			+ " where txif.status <> 3"
			+ " and (?1 is null or txif.invoice_no=?1) "
			+ " and (?2 is null or txif.invoice_code=?2)"
			+ " and (?3 is null or txif.id<>?3)"
			,nativeQuery=true)
	public Integer valInvoiceInfo(String invoiceNo, String invoiceCode, Long tid);

	/**
	 * 根据发票号和发票代码查询发票记录
	 * @param delete
	 * @param invoiceNo
	 * @param invoiceCode
	 * @return
	 */
	CreditInvoiceEntity findByStatusNotAndInvoiceNoAndInvoiceCode(int delete,
			String invoiceNo, String invoiceCode);

	//删除发票记录
	@Transactional
	@Modifying(clearAutomatically = true)
	@Query(value="DELETE FROM tb_xa_invoice_info where id = ?1 ", nativeQuery=true)
	Integer deleteById(Long tid);

	/**
	 * 根据发票字节流判断是否已验真
	 * @version 2018年10月9日
	 * @param uploadBuffer
	 * @return
	 */
	@Query(value="select * from tb_xa_invoice_info where invoice_flow = ?1 and check_true_status <> 0",nativeQuery=true)
	CreditInvoiceEntity findByFlow(String uploadBuffer);
	
	@Transactional
	@Modifying(clearAutomatically = true)
	@Query(value="update tb_xa_invoice_info set check_invoice_code =?2, check_invoice_no =?3,sup_uncert= ?4, pur_uncert= ?5,  check_invoice_amount = ?6,check_invoice_date = ?7 ,invoice_flow = ?8,check_true_status =?9  where id = ?1", nativeQuery=true)
	Integer updateCheckInvoice(Long tid, String invoiceDataCode, String invoiceNumber, String salesTaxpayerNum, String taxpayerNumber, BigDecimal totalTaxSum, Date billingTime, String invoiceBuffer, int i);



}
